/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.calc.thrift.STATUS;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxChangeStatusModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogInModel.class);
    public static final AjaxChangeStatusModel Instance = new AjaxChangeStatusModel();

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();

        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;

        try {
            out = resp.getWriter();
            if (null != req.getParameter("id") && Util.isInteger(req.getParameter("id"))
                    && null != req.getParameter("status")) {

                profiler.push(this.getClass(), "output");
                ProfileSession profileSession = checkLogIn(req);
                Profile profile = getClientWithCache().getaLoad(profileSession.getId());
                if (null != profile && (profile.getRole().equals(ROLE.ADMIN))) {
                    int profileId = Integer.parseInt(req.getParameter("id"));
                    STATUS status = STATUS.valueOf(req.getParameter("status"));
                    boolean result = getClient().changeStatus(profileId, status);
                    if (result) {
                        getClientWithCache().removeCache(profileId);
                        out.println(Util.toJSON("SUCCESS", getProperties().get("en.changeStatus.succeeded")));
                    } else {
                        out.println(Util.toJSON("ERROR", getProperties().get("en.changeStatus.failed")));
                    }
                } else {
                    showError(out, getProperties().get("en.persissionDenied"));
                }
            } else {
                out.println(Util.toJSON("ERROR", getProperties().get("en.invalidParams")));
            }

            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
